package com.sunday.xxl.job.autoconfiguration;

import brave.Tracing;
import com.sunday.xxl.job.trace.TraceConstants;
import com.sunday.xxl.job.trace.TraceXxlJobAspect;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * xxlJob自动配置
 * Configuration    从Spring3.0，@Configuration用于定义配置类，可替换xml配置文件，被注解的类内部包含有一个或多个被@Bean注解的方法，这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描，并用于构建bean定义，初始化Spring容器。
 * EnableConfigurationProperties    如果一个配置类只配置@ConfigurationProperties注解，而没有使用@Component，那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
 * AutoConfigureBefore  在某些类装配之前加载
 * Import   注解把用到的bean导入到了当前容器中。也可以导入一个配置类
 *
 * @author zsy
 * @since 2022/10/23
 */
@Slf4j
@Configuration
@AutoConfigureBefore({Tracing.class})
@ConditionalOnProperty(prefix = TraceConstants.XXL_JOB_PREFIX, value = "adminAddresses")
@EnableConfigurationProperties({XxlJobProperties.class})
@RequiredArgsConstructor
public class XxlJobAutoConfiguration {

    private final XxlJobProperties xxlJobProperties;

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {

        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdminAddresses());
        xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());

        XxlJobProperties.XxlJobExecutorProperties executor = xxlJobProperties.getExecutor();

        xxlJobSpringExecutor.setAppname(executor.getAppName());
        xxlJobSpringExecutor.setIp(executor.getIp());
        xxlJobSpringExecutor.setPort(executor.getPort());
        xxlJobSpringExecutor.setLogPath(executor.getLogPath());
        xxlJobSpringExecutor.setLogRetentionDays(executor.getLogRetentionDays());

        return xxlJobSpringExecutor;
    }

    @Bean
    public TraceXxlJobAspect traceXxlJobAspect(Tracing tracing) {
        log.info(">>>>>>>>>>> xxl-job trace config init.");
        return new TraceXxlJobAspect(tracing);
    }


}
